package fr.nfan.android;

import java.util.ArrayList;
import java.util.List;

import android.os.Vibrator;

public class VibratorCommand {

	private List<Long> pattern = new ArrayList<Long>();
	
	private Vibrator vibrator;
	private boolean recording = false;
	
	public VibratorCommand(Vibrator vibrator) {
		this.vibrator = vibrator;
	}
	
	public void play(String pattern) {
		setPattern(pattern);
		play();
	}
	public void play() {
		vibrator.vibrate(toArray(pattern), -1);
	}
	public void setPattern(String pattern) {
		this.pattern = toList(pattern);
	}
	public void startRecord() {
		 pattern = new ArrayList<Long>();
		 pattern.add(0l);
		 recording = true;
	}
	public void stopRecord() {
		recording = false;
	}
	public boolean isRecording() {
		return recording;
	}
	public void addVibe(long duration) {
		pattern.add(duration);
	}
	
	public String getPattern() {
		if (pattern != null) {
			return pattern.toString().replace("[", "").replace("]", "").replace(" ", "");
		}
		return null;
	}
	
	private List<Long> toList(String pattern) {
		String[] durations = pattern.replace(" ", "").split(",");
		List<Long> patternList = new ArrayList<Long>();
		for (int i = 0; i < durations.length; i++) {
			patternList.add(Long.valueOf(durations[i]));
		}
		return patternList;
	}
	
	private long[] toArray(List<Long> pattern) {
		long[] result = new long[pattern.size()];
		
		if (pattern.size() > 0) {
			int i = 0;
			for (Long l : pattern) {
				result[i++] = l;
			}
		}
		
		return result;
	}
	
}
